package com.lc.qianrenshiye.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lc.qianrenshiye.BaseApplication;
import com.lc.qianrenshiye.R;
import com.lc.qianrenshiye.adapter.CutAdapter;
import com.lc.qianrenshiye.adapter.CutPopAdapter;
import com.lc.qianrenshiye.adapter.FullCutAdapter;
import com.lc.qianrenshiye.adapter.ShopCarAdapter;
import com.lc.qianrenshiye.conn.CutPriceListPost;
import com.lc.qianrenshiye.uitls.MyToast;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/1.
 */
public abstract class CutPriceDialog extends Dialog {

    private List<CutPriceListPost.PercentPriceEntity> cutLists = new ArrayList<>();
    private List<CutPriceListPost.FullCutPriceEntity> fullCutLists = new ArrayList<>();
    private List<CutPriceListPost.PercentPriceEntity> poplists = new ArrayList<>();//pop 的下拉列表
    private CutAdapter cutAdapter;
    private FullCutAdapter fullCutAdapter;

    private String cutPrice;
    private int cutSelPosition = -1;

    private int fullCutSelPosition = -1;
    private PopupWindow mPopupWindow;

    private EditText dialog_cut_price_cancel_full_cut_money_et;
    private TextView cut_price_cut_discount_tv;

    private String cutType = "0"; // 满减类型 0减 1百分比 2 满减

    private boolean isClickCut; //控制 edittext 监听文字变化刷新的 点击gv 不让刷新

    private CutPriceListPost cutPriceListPost = new CutPriceListPost(new AsyCallBack<CutPriceListPost.CutPriceListEntity>() {

        @Override
        public void onSuccess(String toast, int type, CutPriceListPost.CutPriceListEntity cutPriceListEntity) throws Exception {

            cutLists.addAll(cutPriceListEntity.percentPriceEntityList);
            poplists.addAll(cutPriceListEntity.percentPriceEntityList);
            fullCutLists.addAll(cutPriceListEntity.fullCutPriceEntityList);

            cutAdapter.notifyDataSetChanged();
            fullCutAdapter.notifyDataSetChanged();

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            MyToast.showToast(toast, getContext());
        }
    });

    public CutPriceDialog(final Context context, final String price) {
        super(context, R.style.CutPriceDialog);

        setContentView(R.layout.dialog_cut_price);

        GridView cut_price_cut_gv = (GridView) findViewById(R.id.cut_price_cut_gv);
        RelativeLayout dialog_cut_price_cancle_rl = (RelativeLayout) findViewById(R.id.dialog_cut_price_cancle_rl);
        TextView dialog_cut_price_submit_tv = (TextView) findViewById(R.id.dialog_cut_price_submit_tv);
        TextView dialog_cut_price_cancel_full_cut_tv = (TextView) findViewById(R.id.dialog_cut_price_cancel_full_cut_tv);
        dialog_cut_price_cancel_full_cut_money_et = (EditText) findViewById(R.id.dialog_cut_price_cancel_full_cut_money_et);
        TextView cut_price_cut_cancel_tv = (TextView) findViewById(R.id.cut_price_cut_cancel_tv);
        cut_price_cut_discount_tv = (TextView) findViewById(R.id.cut_price_cut_discount_tv);
        GridView dialog_cut_price_cancel_full_cut_gv = (GridView) findViewById(R.id.dialog_cut_price_cancel_full_cut_gv);
        LinearLayout cut_price_cut_discount_ll = (LinearLayout) findViewById(R.id.cut_price_cut_discount_ll);

        cutPrice = price;

        cut_price_cut_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (cutSelPosition != position) {

                    cutAdapter.selPosition = position;

                    cutAdapter.notifyDataSetChanged();

                    cut_price_cut_discount_tv.setText(Float.parseFloat(cutLists.get(position).percent) / 10 + "折");

                    cutSelPosition = position;

                    // 顺序不能变啊
                    isClickCut = true;

                    //选择折扣  就让满减 取消
                    dialog_cut_price_cancel_full_cut_money_et.setText("0");

                    cancleFullCut("");
                }



            }
        });

        dialog_cut_price_cancel_full_cut_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                Log.e("fullCutSelPosition", "fullCutSelPosition" + fullCutSelPosition + "position" + position);

                if (fullCutSelPosition != position) {

                    dialog_cut_price_cancel_full_cut_money_et.setText(fullCutLists.get(position).money);

                    fullCutAdapter.selFullCutPosition = position;

                    fullCutAdapter.notifyDataSetChanged();

                    fullCutSelPosition = position;

                    //选择满减让折扣取消
                    cut_price_cut_discount_tv.setText("0折");

                    cancelCut();
                }

            }
        });



        cut_price_cut_gv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(10));
        dialog_cut_price_cancel_full_cut_gv.setVerticalSpacing(ScaleScreenHelperFactory.getInstance().getWidthHeight(10));

        cut_price_cut_gv.setAdapter(cutAdapter = new CutAdapter(context, cutLists));
        dialog_cut_price_cancel_full_cut_gv.setAdapter(fullCutAdapter = new FullCutAdapter(context, fullCutLists));

        dialog_cut_price_cancel_full_cut_money_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {

                if (!isClickCut) {

                    cancleFullCut("");

                    dialog_cut_price_cancel_full_cut_money_et.setSelection(s.length());

                    cancelCut();

                    cut_price_cut_discount_tv.setText("0折");

                }

                isClickCut = false;

            }
        });


        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (v.getId()) {

                    case R.id.dialog_cut_price_cancle_rl://底部取消

                        dismiss();

                        break;

                    case R.id.cut_price_cut_discount_ll://折扣

                        initPopupWindow(context, cut_price_cut_discount_tv);

                        break;

                    case R.id.cut_price_cut_cancel_tv://取消折扣

                        cutPrice = price;

                        cut_price_cut_discount_tv.setText("0折");

                        cancelCut();

                        break;

                    case R.id.dialog_cut_price_cancel_full_cut_tv://取消满减

                        cutPrice = price;

                        dialog_cut_price_cancel_full_cut_money_et.setText("0");

                        cancleFullCut("");

                        break;

                    case R.id.dialog_cut_price_submit_tv://提交

                        String percent = cut_price_cut_discount_tv.getText().toString().replaceAll("折", "");
                        String fullCut = dialog_cut_price_cancel_full_cut_money_et.getText().toString();

                        if (!percent.equals("0") && !fullCut.equals("0")) { // 打折和满减都不等于0的时候，先计算打折 然后算满减

                            cutPrice = new BigDecimal(percent).divide(new BigDecimal("10")).multiply(new BigDecimal(price)).toString();

                            cutPrice = new BigDecimal(cutPrice).subtract(new BigDecimal(fullCut)).toString();

                        } else if (!percent.equals("0")) {

                            cutPrice = new BigDecimal(percent).divide(new BigDecimal("10")).multiply(new BigDecimal(price)).toString();

                            cutType = "1";

                        } else if (!fullCut.equals("0")) {

                            cutPrice = new BigDecimal(price).subtract(new BigDecimal(fullCut)).toString();

                            cutType = "2";

                        }

                        //判断钱小于0  就让钱等于0.01
                        if (new BigDecimal(cutPrice).signum() != 1) {

                            cutPrice = "0.01";

                            fullCut = new BigDecimal(price).subtract(new BigDecimal("0.01")).toString();
                        }

                        DecimalFormat decimalFormat = new DecimalFormat("0.00");

                        cutPrice = decimalFormat.format(new BigDecimal(cutPrice));

                        switch (cutType) {

                            case "0":
                                // cutPrice 默认等于 price 就是传进来的价钱
                                onConfirm(price, cutPrice, cutType, "0");
                                break;

                            case "1":
                                // cutPrice 默认等于 price 就是传进来的价钱
                                onConfirm(price, cutPrice, cutType, String.valueOf(Float.parseFloat(percent) * 10).replace(".0", ""));
                                break;

                            case "2":
                                // cutPrice 默认等于 price 就是传进来的价钱
                                onConfirm(price, cutPrice, cutType, fullCut);
                                break;
                        }



                        break;
                }
            }
        };


        cutPriceListPost.sid = BaseApplication.BasePreferences.readShopId();
        cutPriceListPost.execute(context);


        dialog_cut_price_cancle_rl.setOnClickListener(listener);
        dialog_cut_price_submit_tv.setOnClickListener(listener);
        dialog_cut_price_cancel_full_cut_tv.setOnClickListener(listener);
        cut_price_cut_cancel_tv.setOnClickListener(listener);
        cut_price_cut_discount_ll.setOnClickListener(listener);

    }

    private void cancleFullCut(String price) {

        if (fullCutSelPosition != -1) {

            fullCutAdapter.selFullCutPosition = -1;//  不大于0 刷新 就是不选中
            fullCutAdapter.notifyDataSetChanged();

            fullCutSelPosition = -1;
        }


        //下面方法留着,如果上面settext时候 adapter刷新不对 就用下面方法

//        if(TextUtils.isEmpty(price)){
//
//            if (fullCutSelPosition != -1) {
//
//                fullCutAdapter.selFullCutPosition = -1;//  不大于0 刷新 就是不选中
//                fullCutAdapter.notifyDataSetChanged();
//
//                fullCutSelPosition = -1;
//            }
//
//        }else{
//
//            boolean isCancel = false;
//
//            for(int i=0; i < fullCutLists.size(); i++){
//
//                if(price.equals(fullCutLists.get(i).money)){
//
//                    fullCutAdapter.selFullCutPosition = i;
//                    fullCutAdapter.notifyDataSetChanged();
//
//                    fullCutSelPosition = i;
//
//                    isCancel = true;
//
//                }
//
//            }
//
//            if(!isCancel){
//
//                fullCutAdapter.selFullCutPosition = -1;//  不大于0 刷新 就是不选中
//                fullCutAdapter.notifyDataSetChanged();
//
//                fullCutSelPosition = -1;
//
//            }
//
//        }

    }

    private void cancelCut() {

        if (cutSelPosition != -1) {

            cutAdapter.selPosition = -1;
            cutAdapter.notifyDataSetChanged();

            cutSelPosition = -1;

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) findViewById(R.id.dialog_cut_price_ll));
        getWindow().setGravity(Gravity.TOP);
    }

    public void initPopupWindow(Context context, final TextView cut_price_cut_discount_tv) {

        View popupView = BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) getLayoutInflater().inflate(R.layout.item_popview, null)));

        ListView item_popview_lv = (ListView) popupView.findViewById(R.id.item_popview_lv);

        CutPopAdapter cutPopAdapter = new CutPopAdapter(context, poplists);

        item_popview_lv.setAdapter(cutPopAdapter);

        item_popview_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                isClickCut = true;

                cancelCut();

                Log.e("---", position + "");

                cut_price_cut_discount_tv.setText(Float.parseFloat(poplists.get(position).percent) / 10 + "折");

                dialog_cut_price_cancel_full_cut_money_et.setText("0");

                cancleFullCut("");

                mPopupWindow.dismiss();
            }
        });

        mPopupWindow = new PopupWindow(popupView, cut_price_cut_discount_tv.getWidth(), LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);

        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());

        mPopupWindow.showAsDropDown(cut_price_cut_discount_tv);


    }

    public abstract void onConfirm(String price, String cutPrice, String cutType, String fullcut);


}
